package com.fzc.rhinooffice.common;

import java.io.StringReader;

import org.json.JSONException;
import org.json.JSONObject;

import com.fzc.rhinooffice.R;
import com.fzc.rhinooffice.common.utils.CommonUtil;
import com.fzc.rhinooffice.common.utils.JsonUtil;
import com.fzc.rhinooffice.common.utils.StringUtil;
import com.fzc.rhinooffice.module.entity.VersionInfo;
import com.lidroid.xutils.util.LogUtils;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Handler;
import android.os.IBinder;
import android.util.JsonReader;
import android.widget.RemoteViews;

@SuppressLint("NewApi")
public class UpdateService extends Service {
	
	
	private Context context;
	 /***
     * 创建通知栏
     */
    RemoteViews mViews;
    /** 应用名称 */
    private String app_name;
    /** 通知管理器 */
    private NotificationManager notificationManager;
    /** 通知 */
    private Notification notification;
    /** 点击通知跳转 */
    private Intent mUpdateIntent;
    /** 等待跳转 */
    private PendingIntent mPendingIntent;
    /** 通知ID */
    private final int notification_id = 0;
	
    private VersionInfo remoteVersonInfo;
    
    private VersionInfo localVersonInfo;
    
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		context = getApplicationContext();
		
		checkRemoteVersion();		
		
		//createNotification();
		localVersonInfo = new VersionInfo();
		
		return super.onStartCommand(intent, flags, startId);
	}

	
	private final Handler mHandler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			
			switch (msg.what) {
			case 7:
				JSONObject jsonObject = (JSONObject) msg.obj;
				if (jsonObject != null) {
							
					remoteVersonInfo = JsonUtil.analysis_version_infor(StringUtil.StringToJsonReader(jsonObject.toString()));
					localVersonInfo.ver = getVersionName();
					LogUtils.i("本地版本号：："+localVersonInfo.ver);
					if(localVersonInfo.ver!=null && remoteVersonInfo.ver!=null){
						showUpdataDialog();
					}
				}
				break;

			case -7:
				
				break;
			}
		};
	};
	
	private void checkRemoteVersion() {
        if (CommonUtil.isNetworkConnected(context)) {
        	LogUtils.i("开始检测更新\n");
        	//获取服务端版本信息
            RemoteInvoke.verupdate(mHandler, "2015-05-18");
        }

	}

	
	/**
	 * 
	 * @param mContext 上下文信息
	 * @return	版本信息
	 * @throws NameNotFoundException 
	 * @throws Exception
	 */
	private String getVersionName() {  
	    //获取packagemanager的实例   
	    PackageManager packageManager = context.getPackageManager();  
	    //getPackageName()是你当前类的包名，0代表是获取版本信息  
	    PackageInfo packInfo = null;
		try {
			packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return null;
		}  
	    return packInfo.versionName;   
	} 
	
	/* 
	 *  
	 * 弹出对话框通知用户更新程序  
	 *  
	 * 弹出对话框的步骤： 
	 *  1.创建alertDialog的builder.   
	 *  2.要给builder设置属性, 对话框的内容,样式,按钮 
	 *  3.通过builder 创建一个对话框 
	 *  4.对话框show()出来   
	 */  
	public void showUpdataDialog() {  
	    AlertDialog.Builder builer = new Builder(context) ;   
	    builer.setTitle("软件升级");  
	    builer.setMessage("发现新版本,建议立即更新使用");
	    //当点确定按钮时从服务器上下载 新的apk 然后安装   
	    builer.setPositiveButton("更新", new OnClickListener() {  
		    public void onClick(DialogInterface dialog, int which) {  
		    		//下载新版本apk
		    	createNotification();
		    }     
	    });  
	    //当点取消按钮时进行登录  
	    builer.setNegativeButton("暂不更新", new OnClickListener() {  
	        public void onClick(DialogInterface dialog, int which) {  
	           stopSelf();
	        }  
	    });  
	    AlertDialog dialog = builer.create();  
	    dialog.show();  
	} 
	
	private void createNotification() {
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        android.app.Notification.Builder builder = new Notification.Builder(this);
        mViews = new RemoteViews(getPackageName(), R.layout.view_custom_progress);
        mViews.setImageViewResource(R.id.custom_progress_icon, R.drawable.ic_launcher);
        mViews.setTextViewText(R.id.tv_custom_progress_title, "犀牛新版本正在下载");
        mViews.setTextViewText(R.id.tv_custom_progress_status, "0%");
        mViews.setProgressBar(R.id.custom_progressbar, 100, 0, false);
        builder.setContent(mViews);
        mUpdateIntent = new Intent(Intent.ACTION_MAIN);
        mUpdateIntent.addCategory(Intent.CATEGORY_HOME);
        mPendingIntent = PendingIntent.getActivity(this, 0, mUpdateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(mPendingIntent);
        builder.setTicker("开始下载，点击可查看");
        //builder.setSmallIcon(R.drawable.ic_launcher).setWhen(System.currentTimeMillis()).setAutoCancel(true);// 设置可以清除
        notification = builder.build();
        notificationManager.notify(notification_id, notification);
		
	}
}
